<template>
    <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" style="width:700px;">
        <el-form :model="addBaseTaskForm" ref="addBaseTaskRef" :rules="addBaseTaskrules">
            <el-form-item label="资产部门" :label-width="formLabelWidth" prop="departmentName">
                <el-select v-model="addBaseTaskForm.departmentId" placeholder="请选择资产部门" style="width:100%"
                    @change="changeDepartHandle" clearable>
                    <el-option v-for="item in departmentList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="盘点人" :label-width="formLabelWidth" prop="teacherNumbers">
                <!-- <el-select v-model="addBaseTaskForm.teacherNumbers" multiple filterable :filter-method="serachTeacher"
                    placeholder="请选择盘点人 " style="width:100%" clearable>
                    <template #header>
                        <el-input></el-input>
                    </template>
<el-option v-for="item in teacherList" :key="item.id" :label="item.name" :value="item.teacherNumber" />
</el-select> -->


                <el-tree-select v-model="addBaseTaskForm.teacherNumbers" :data="allTeacherList" multiple
                    :render-after-expand="false" show-checkbox style="width: 100%" @change="handleChangeCascader"
                    placeholder="请选择盘点人" />


                <!-- <el-tree :data="allTeacherList" :props="defaultProps" node-key="id"
                    @node-click="handleNodeClick"></el-tree> -->
            </el-form-item>
            <el-form-item label="任务标题" :label-width="formLabelWidth" prop="title">
                <el-input v-model="addBaseTaskForm.title" autocomplete="off" ref="name"
                    placeholder="请填写任务标题"></el-input>
            </el-form-item>
            <el-form-item label="任务描述" :label-width="formLabelWidth" prop="content">
                <el-input v-model="addBaseTaskForm.content" autocomplete="off" ref="name"
                    placeholder="请填写任务描述"></el-input>
            </el-form-item>
            <el-form-item label="开始日期" :label-width="formLabelWidth" prop="startTimeStr" format="YYYY-MM-DD">
                <el-config-provider :locale="locale">
                    <el-date-picker v-model="addBaseTaskForm.startTimeStr" type="date" placeholder="请选择开始时间"
                        style="width:100%;" @change="changeTime" />
                </el-config-provider>
            </el-form-item>
            <el-form-item label="结束日期" :label-width="formLabelWidth" prop="entTimeStr" format="YYYY-MM-DD">
                <el-config-provider :locale="locale">
                    <el-date-picker v-model="addBaseTaskForm.entTimeStr" type="date" placeholder="请选择结束时间"
                        style="width:100%;" @change="changeTime1" />
                </el-config-provider>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel()">取消</el-button>
                <el-button type="primary" @click="save()">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { formatTime, editTeacherData } from "@/utils/dateFormat";
import { ElMessage, ElForm } from "element-plus";
import { vxRule } from "@/utils/validator";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { API_BASE_NAME, API_BASE_NAME1 } from "../../constants"
// import Node from 'element-plus/es/components/tree/src/model/node'

export default {
    name: "AddBaseAddress",
    components: { ElForm, ElMessage },
    data() {
        return {
            dialogFormVisible: ref(false),
            schoolName: API_BASE_NAME,
            schoolName1: API_BASE_NAME1,
            formLabelWidth: "120px",
            title: "",
            personnelType: "",
            id: '',
            teacherList: [],
            teacherList1: [],
            quarter: "",
            taskData: {},
            studentNumber: [],
            addBaseTaskForm: {
                title: "",
                content: "",
                startTimeStr: "",
                entTimeStr: "",
                timeDate: '',
                departmentId: "",
                departmentName: "",
                teacherNumbers: "",
                teacher_names: "",
                teacher: "",
            },
            // 校验规则
            addBaseTaskrules: {
                title: vxRule(true, null, "blur"),
                // content: vxRule(true, null, "blur"),
                timeDate: vxRule(true, null, "blur"),
                departmentId: vxRule(true, null, "blur"),
                teacherNumbers: vxRule(true, null, "blur"),
                departmentName: vxRule(true, null, "blur"),
                startTimeStr: vxRule(true, null, "blur"),
                entTimeStr: vxRule(true, null, "blur"),
            },
            departmentList: [],
            departmentList1: [],
            options: [],
            user: {},
            allTeacherList: [],
            allList: [],
            dataEdit: {
                "1": {
                    name: this.schoolName,
                    id: 1,
                    departments: {
                        "2021级1部": {
                            departmentName: null, teachers: [
                                { teacherName: '陈玉景', teacherNumber: '130200' },
                                { teacherName: '崔利花', teacherNumber: '130351' },
                            ]
                        },
                        "2021级2部": {
                            departmentName: null, teachers: [
                                { teacherName: '陈玉景', teacherNumber: '130200' },
                                { teacherName: '崔利花', teacherNumber: '130351' },
                            ]
                        }
                    },
                },
                "2": {
                    name: this.schoolName1,
                    id: 1,
                    departments: {
                        "2021级3部": {
                            departmentName: null, teachers: [
                                { teacherName: '陈玉景', teacherNumber: '130200' },
                            ]
                        },
                    }
                },
            },
            data: [
                {
                    laebl: this.schoolName,
                    value: "1",
                    children: [
                        {
                            laebl: "2021级1部",
                            value: "2021级1部",
                            departmentName: null, children: [
                                { teacherName: '陈玉景', teacherNumber: '130200', label: '陈玉景', value: '130200' },
                                { teacherName: '崔利花', teacherNumber: '130351', label: '崔利花', value: '130351' },
                            ]
                        },
                        {
                            laebl: "2021级2部",
                            value: "2021级2部",
                            departmentName: null, children: [
                                { teacherName: '陈玉景', teacherNumber: '130200', label: '陈玉景', value: '130200' },
                                { teacherName: '崔利花', teacherNumber: '130351', label: '崔利花', value: '130351' },
                            ]
                        }
                    ]
                },
                {
                    laebl: this.schoolName1,
                    value: '2',
                    children: [{
                        laebl: "2021级3部",
                        value: "2021级3部",
                        departmentName: null, children: [
                            { teacherName: '陈玉景', teacherNumber: '130200', label: '陈玉景', value: '130200' },
                        ]
                    }],
                },
            ],
            aaaList: [],
            defaultProps: {},
            allTeacherData: [],
        };
    },
    setup() {
        return {
            locale: zhCn,
        };
    },
    computed: {
    },
    mounted() {
        // this.getCurrentQuarter()
        this.user = JSON.parse(sessionStorage.getItem('user'))
        // this.getListmy()
    },
    methods: {
        getListmy() {
            httpService("/javaApi/baseTeacherDepartment/teacherTree", {}, "get").then(
                (data) => {
                    this.editData(data)
                    this.getAllTeachers(data)
                    // this.aaaList = data
                    // let allTeachers = [];
                    // for (const schoolId in data) {
                    //     const school = data[schoolId];
                    //     for (const departmentId in school.departments) {
                    //         const department = school.departments[departmentId];
                    //         allTeachers = allTeachers.concat(department.teachers);
                    //     }
                    // }

                    // const uniqueTeacherNumbers = new Set();
                    // const uniqueTeachers = [];
                    // allTeachers.forEach(teacher => {
                    //     if (!uniqueTeacherNumbers.has(teacher.teacherNumber)) {
                    //         uniqueTeacherNumbers.add(teacher.teacherNumber);
                    //         uniqueTeachers.push(teacher);
                    //     }
                    // });

                    // this.allList = uniqueTeachers
                    // console.log(444,this.allList );
                }
            );

        },

        getAllTeachers(schoolData) {
            const allTeachers = Object.values(schoolData).flatMap(school =>
                Object.values(school.departments).flatMap(department => department.teachers)
            );
            this.allList = allTeachers
            // console.log(222, allTeachers);
        },

        editData(valueData) {
            setTimeout(() => {
                const convertedData = [];
                // 遍历原始数据的每个学校对象  
                for (const schoolKey in valueData) {
                    const school = valueData[schoolKey];
                    // 构造学校的转换对象  
                    const schoolObject = {
                        // schoolKey
                        label: school.name,
                        value: schoolKey,
                        children: [],
                    };
                    // 遍历学校的每个部门对象  
                    for (const departmentKey in school.departments) {
                        const department = school.departments[departmentKey];
                        // 构造部门的转换对象  
                        const departmentObject = {
                            label: departmentKey,
                            value: departmentKey,
                            departmentName: department.departmentName,
                            children: [],
                        };
                        // 遍历部门的每个老师对象，并添加到 children 数组中  
                        department.teachers.forEach(teacher => {
                            const teacherObject = {
                                teacherName: teacher.teacherName,
                                teacherNumber: teacher.teacherNumber,
                                label: teacher.teacherName,
                                value: teacher.teacherNumber,
                            };
                            departmentObject.children.push(teacherObject);
                        });
                        // 将部门对象添加到学校的 children 数组中  
                        schoolObject.children.push(departmentObject);
                    }
                    // 将学校对象添加到转换后的数组中  
                    convertedData.push(schoolObject);
                }
                this.allTeacherList = convertedData


            }, 0);
        },
        getCurrentQuarter() {
            const currentMonth = new Date().getMonth() + 1;
            const currentYear = new Date().getFullYear();
            let quarter = Math.ceil(currentMonth / 3);
            if (quarter == 1) {
                quarter = "第一季度"
            } else if (quarter == 2) {
                quarter = "第二季度"
            } else if (quarter == 3) {
                quarter = "第三季度"
            } else if (quarter == 4) {
                quarter = "第四季度"
            }
            this.quarter = quarter
            this.addBaseTaskForm.title = `${currentYear}${quarter}盘点任务`
            return quarter;
        },
        changeTime(value) {
            this.addBaseTaskForm.startTimeStr = formatTime(value)
        },
        changeTime1(value) {
            this.addBaseTaskForm.entTimeStr = formatTime(value)
        },
        closeDialog() {
            this.clear();
        },
        cancel() {
            this.dialogFormVisible = false;
            this.clear();
        },
        getTaskById(id) {
            httpService("/javaApi/faTask/queryById", { id: id }, "get").then(
                (data) => {
                    this.taskData = data
                    this.addBaseTaskForm = data;
                    if (data.teacherNames) {
                        // this.addBaseTaskForm.teacherNumbers = data.teacherNames.split(",")
                        this.addBaseTaskForm.teacherNumbers = data.teacherNumbers.split(",")
                    }
                    this.addBaseTaskForm.timeDate = [data.startTime, data.entTime]
                }
            );
        },
        clear() {
            this.dialogFormVisible = false;
            //清空form
            this.id = ""

            this.addBaseTaskForm.title = ""
            this.addBaseTaskForm.content = ""
            this.addBaseTaskForm.startTimeStr = ""
            this.addBaseTaskForm.entTimeStr = ""
            this.addBaseTaskForm.timeDate = ''
            this.addBaseTaskForm.departmentId = ""
            this.addBaseTaskForm.departmentName = ""
            this.addBaseTaskForm.teacherNumbers = ""
            this.addBaseTaskForm.teacher_names = ""
            this.addBaseTaskForm.teacher = ""
        },
        save() {
            if (this.departmentList) {
                const data = this.departmentList.filter(item => item.id == this.addBaseTaskForm.departmentId)
                if (data.length > 0) {
                    this.addBaseTaskForm.departmentName = data[0].name
                }
            }

            this.$refs.addBaseTaskRef.validate((valid) => {
                if (valid) {
                    let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据
                    params.append("title", this.addBaseTaskForm.title);
                    params.append("content", this.addBaseTaskForm.content);
                    params.append("departmentId", this.addBaseTaskForm.departmentId);
                    params.append("departmentName", this.addBaseTaskForm.departmentName);
                    params.append("startTimeStr", this.addBaseTaskForm.startTimeStr + " " + "00:00:00");
                    params.append("endTimeStr", this.addBaseTaskForm.entTimeStr + " " + "00:00:00");
                    params.append("status", 0);
                    if (this.id) {
                        let numberData = [] 
                        this.addBaseTaskForm.teacherNumbers.forEach(item => {
                            const number = this.allList.filter(val => val.teacherNumber == item)
                            if (number.length > 0) {
                                numberData.push(number[0].teacherName)
                            }
                        })
                        params.append("teacherNumbers", this.addBaseTaskForm.teacherNumbers.join(','));
                        params.append("teacherNames", numberData.join(',')); 
                        params.append("id", this.id);
                        httpService("/javaApi/faTask/edit", params, "post").then(
                            (data) => {
                                if (data.code == 200) {
                                    ElMessage.success("修改成功");
                                    this.clear();
                                    //刷新父组件的数据
                                    this.$parent.getFaTaskList();
                                } else {
                                    ElMessage.error("修改失败");
                                }
                            }
                        );
                    } else { 
                        const numbers = this.addBaseTaskForm.teacherNumbers.join(',')
                        params.append("teacherNumbers", numbers);
                        params.append("teacherNames", this.addBaseTaskForm.teacher_names);
                       
                        httpService("/javaApi/faTask/add", params, "post").then(
                            (data) => {
                                if (data.code == 200) {
                                    ElMessage.success("添加成功");
                                    this.clear();
                                    this.$parent.getFaTaskList();
                                } else {
                                    ElMessage.error("添加失败");
                                }
                            }
                        );
                    }
                } else {
                    return false;
                }
            });
        },
        changeDepartHandle(value) {
        },
        getDepartmentList() {
            httpService("/javaApi/faDepartment/list/1/100", { campus: this.user.campus }, "get").then(
                (data) => {
                    this.departmentList = data.list
                }
            );
        },
        getDepartmentList1() {
            httpService("/javaApi/baseDepartment/list/1/100", {}, "get").then(
                (data) => {
                    if (data.list) {
                        this.departmentList1 = data.list.map(item => {
                            return {
                                "value": item.id,
                                "label": item.name,
                                "children": [],
                            }
                        })
                    }
                    if (this.departmentList1) {
                        this.getChangeTeacherr()
                    }
                }
            );
        },
        getChangeTeacherr(value) {
            // this.departmentList1.map(item => {
            //     httpService(
            //         "/javaApi/baseTeacherDepartment/list/1/2000",
            //         { "departmentId": item.value },
            //         "get"
            //     ).then((data) => {
            //         let arr = []
            //         if (data.list) {
            //             arr = data.list.map(val => {
            //                 return {
            //                     "label": val.teacherName,
            //                     "value": val.teacherNumber,
            //                 }
            //             })
            //         }
            //         item.children = arr
            //     });
            // })
        },
        handleChangeCascader(value) {
            // console.log(this.addBaseTaskForm.teacherNumbers);
            if (this.teacherList) {
                let data = []
                if (this.addBaseTaskForm.teacherNumbers.length > 0) {
                    this.addBaseTaskForm.teacherNumbers.forEach(item => {
                        let value = this.allList.filter(val => val.teacherNumber == item)
                        data = data.concat(value)
                        if (data.length > 0) { this.addBaseTaskForm.teacher_names = data.map(item => item.teacherName).join(',') }
                    })
                    console.log(this.addBaseTaskForm.teacher_names);
                } else {
                    this.addBaseTaskForm.teacher_names = ''
                }
            }
            // if (this.allList) {
            //     let data = []
            //     if (this.addBaseTaskForm.teacherNumbers.length > 0) {
            //         this.addBaseTaskForm.teacherNumbers.forEach(item => {
            //             let value = this.allList.filter(val => val.teacherNumber == item)
            //             data = data.concat(value)
            //             if (data.length > 0) { this.addBaseTaskForm.teacher_names = data.map(item => item.teacherName).join(',') }
            //         })
            //         // console.log(this.addBaseTaskForm.teacher_names);
            //     } else {
            //         this.addBaseTaskForm.teacher_names = ''
            //     }
            // }

        },
        getBaseTeacherList() {
            httpService(
                "/javaApi/baseTeacher/list/1/10000",
                {},
                "get"
            ).then((data) => {
                this.teacherList = data.list;
            });
        },
        getBaseTeacherList1(id) {
            id ? id : ''
            httpService(
                "/javaApi/baseTeacherDepartment/list/1/2000",
                { departmentId: id },
                "get"
            ).then((data) => {
                this.teacherList1 = data.list;
                let arr = []
                if (data.list) {
                    arr = data.list.map(item => {
                        return {
                            "label": item.teacherName,
                            "value": item.teacherNumber,
                        }
                    })
                }
            });
        },

        serachTeacher(value) {
            let teacher = ''
            value == undefined ? teacher = '' : teacher = value
            httpService("/javaApi/baseTeacher/list/1/10000", { "name": teacher }, "get").then(
                (data) => {
                    this.teacherList = data.list
                }
            );
        },
        getDate(time) {
            const date = new Date(time)
            const year = date.getFullYear();
            const month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
            const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
            const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
            const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
            const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
            const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return formattedDateTime
        },
    },
};
</script>
<style>
.el-dialog__header {
    padding: var(--el-dialog-padding-primary);
    padding-bottom: 10px;
    border-bottom: 1px solid #dedede;
    margin-bottom: 15px;
}
</style>